var TestCreator = (function () {

	var questionNo = 1;
	var counter = 0;
	var optionsArr = ["A", "B", "C", "D", "E", "F", "G", "H"];
	var createdTestId = 0;

	function addOption(currentQuestion) {
		var source = $("#option-layout").html();
		var templ = Handlebars.compile(source);
		var optionsList = currentQuestion.find(".options-list");
		var currentOptionNo = optionsList.find("li").length;
		optionsList.append(templ);
		currentQuestion.find(".option:eq(" + currentOptionNo + ")").text(
			optionsArr[currentOptionNo]);
	};

	function showOptions(sel) {
		var value = sel.options[sel.selectedIndex].value;
		if (value == 0) {
			return;
		}

		var currentQuestion = $(sel).closest(".question-item");
		currentQuestion.find(".options-list").empty();
		for (var i = 0; i < value; i++) {
			addOption(currentQuestion);
		}
		var selectAnswer = currentQuestion.find("#selectCorrectAnswer");
		selectAnswer.empty();
		if (currentQuestion.find("#multiAnswerType").is(":checked")) {
			for (var i = 0; i < value; i++) {
				selectAnswer.append("<input type='checkbox' class='answer' id='" + i + "_" + currentQuestion.attr("id") + "' style='margin:5px' value='" + optionsArr[i] + "'>" + optionsArr[i] + "</input>");
			}
		} else {
			for (var i = 0; i < value; i++) {
				selectAnswer.append("<input type='radio' class='answer' id='" + i + "_" + currentQuestion.attr("id") + "' style='margin:5px' value='" + optionsArr[i] + "'>" + optionsArr[i] + "</input>");
			}
		}
	};

	Handlebars.registerHelper("generateQuestionId", function (
		data) {
		var id = ++counter;
		questionNo++;
		return id;
	});

	Handlebars.registerHelper("currentQuestionId", function (
		data) {
		return questionNo - 1;
	});

	Handlebars.registerHelper("randomId", function (data) {
		return counter;
	});

	function initWizard() {
		var w = $("#wizard");
		w.wizard();
		w.on('change', function (e, data) {
			alert(JSON.stringify(data));
			if (data.step == 2) {
				addTest();
			} else if (data.step == 3) {
				addTestQuestions();
			}
		});
	};

	$(document).ready(function () {
		Handlebars.registerPartial("choose-categories-recursion", $("#choose-categories-recursion-partial").html());

		$(".select-options").live("change", function () {
			showOptions(this);
		});

		$(".answer-type").live("click", function () {

			var selected = -1;
			if ($(this).attr("id") == "singleAnswerType") {
				selected = 1;
			} else if ($(this).attr("id") == "multiAnswerType") {
				selected = 2;
			}
			var currentQuestion = $(this).closest(".question-item");
			var selectAnswer = currentQuestion.find("#selectCorrectAnswer");
			selectAnswer.empty();
			var noOfOptionsSeln = currentQuestion.find(".select-options");
			var value = noOfOptionsSeln.val();
			if (selected == 1) {
				for (var i = 0; i < value; i++) {
					selectAnswer.append("<input type='radio' class='answer' id='" + i + "_" + currentQuestion.attr("id") + "' style='margin:5px' value='" + optionsArr[i] + "'>" + optionsArr[i] + "</input>");
				}
			} else if (selected == 2) {
				for (var i = 0; i < value; i++) {
					selectAnswer.append("<input type='checkbox' class='answer' id='" + i + "_" + currentQuestion.attr("id") + "' style='margin:5px' value='" + optionsArr[i] + "'>" + optionsArr[i] + "</input>");
				}
			}
		});

		$(".save-questions").live("click", function () {
			var questions = new Array();
			for (var i = 0; i < $(".questions-list").children().length; i++) {
				var quesLI = $(".questions-list").children().eq(i);
				var questionId = quesLI.attr("id");

				var question = {};
				question.q = quesLI.find(".question-content").val();
				question.type = quesLI.find("input:radio:checked").data("type");


				var optionsList = quesLI.find(".options-list");
				question.a = new Array();
				for (var j = 0; j < optionsList.children().length; j++) {
					var optLi = optionsList.children().eq(j);
					var opt = {};
					opt.option = optLi.find(".option-content").val();
					if (question.type == "SingleSelect" && quesLI.find("input:radio[id=" + j + "_" + questionId + "]").is(":checked")) {
						opt.answer = true;
					}
					if (question.type == "MultiSelect" && quesLI.find("input:checkbox[id=" + j + "_" + questionId + "]").is(":checked")) {
						opt.answer = true;
					}
					question.a.push(opt);
				}
				questions.push(question);
			}
			var test = {};
			test.questions = questions;
			test.info = {};
			test.info.name = "Test 1";
			test.duration = 600;
			$("#step3").test(test, null);
		});


		$(".add-option").live("click", function () {
			var currentQuestion = $(this).closest(
				".question-item");
			addOption(currentQuestion);
		});

		$(".add-question").live("click", function () {
			alert("Adding Question");
			var source = $("#question-layout").html();
			var templ = Handlebars.compile(source);
			$(".questions-list").append(templ);
			var question = $("#question" + (counter));
			question.find(".question-content").ckeditor();
			question.find(".solution").ckeditor();
		});

		$(".show-hide-options").live("click", function () {
			var currentQuestion = $(this).closest(
				".question-item");
			currentQuestion.find(".options-div")
				.slideToggle();
		});

		$(".remove-question").live("click", function () {
			var questionToBeDeleted = $(this)
				.closest(".question-item");
			var questionNoToBeDeleted = questionToBeDeleted
				.attr("id").substring(8);
			questionToBeDeleted.remove();
			questionNo--;
			var index = 1;
			$(".question-item").each(function (i) {
				var qNoSpan = $(this).find('.question-number span');
				qNoSpan.text("Question Number " + index++);
			});
		});

		$(".remove-option").live("click", function () {
			var optionToBeDeleted = $(this).closest("option-item");
			optionToBeDeleted.remove();
		});

		initWizard();
	});



	function initTree() {
		$("#jstree1").on("select_node.jstree", function (e, data) {
			for (var i = 0; i < data.selected.length; i++) {
				selectedNode = $("#" + data.instance.get_node(data.selected[i]).id);
			}
		}).on("loaded.jstree", function (event, data) {
			$(this).jstree("open_all");
		}).jstree({
			"checkbox": {
				"real_checkboxes": true,
				"real_checkboxes_names": function (n) {
					return [n[0].id, 1];
				},
				"two_state": false
			},
			"themes": {
				"theme": "default",
				"url": "/../../lib/jstree/themes/default/style.css",
				"dots": false
			},
			"plugins": ["themes", "ui", "checkbox", "html_data"]
		});
		$("#jstree1").css("background-color", "white");
	}

	function getTestCategories() {
		//alert("Get Test Categories");
		TestMgtService.getTestCategories(getTestCategories_Result_Creation);
	}

	function getTestCategories_Result_Creation(data) {
		var categoriesWrapper = {};
		categoriesWrapper.categories = data;
		var source = $("#choose-categories-list").html();
		var templ = Handlebars.compile(source);
		//alert(templ(categoriesWrapper));
		$("#chooseCategoryTreeContainer").empty();
		$("#chooseCategoryTreeContainer").append("<div id='jstree1'></div>");
		$("#jstree1").append(templ(categoriesWrapper));
		initTree();
	}

	function addTest() {
		var test = {};
		test.name = $("#testName").val();
		test.code = $("#testName").val();
		test.desc = tinyMCE.get("testDesc").getContent();
		test.instructions = tinyMCE.get("testInstr").getContent();
		test.totalMarks = $("#totalMarks").val();
		test.positiveMarks = $("#marksPerQuestion").val();
		test.negativeMarks = $("#negMarksPerQuestion").val();
		test.createdBy = "Sahil";
		test.active = true;
		test.testType = {};
		test.testType.id = 1;
		test.passMarks = $("#passingMarks").val();
		test.duration = $("#testDuration").val();

		test.categories = new Array();

		for (var i = 0; i < $(".jstree-checked").length; i++) {
			//alert($(".jstree-checked").eq(i).data("id"));
			var category = {};
			category.id = $(".jstree-checked").eq(i).data("id");
			category.name = $(".jstree-checked").eq(i).data("name");
			test.categories.push(category);
		}

		//alert(JSON.stringify(test));
		TestMgtService.addTest(test, addTest_Result);
	}


	function addTest_Result(data) {
		alert("Newly Created Test ID " + data.id);
		createdTestId = data.id;
	}

	function addTestQuestions() {
		var questions = new Array();
		for (var i = 0; i < $(".questions-list").children().length; i++) {
			var quesLI = $(".questions-list").children().eq(i);
			var questionId = quesLI.attr("id");

			var question = {};

			var d = new Date();
			var n = d.getMilliseconds();
			question.code = n;

			question.question = quesLI.find(".question-content").val();
			var type = quesLI.find("input:radio:checked").data("type");

			question.questionType = {};
			if (type == "SingleSelect") {
				question.questionType.id = 1;
			} else {
				question.questionType.id = 2;
			}

			question.formatType = {};
			question.formatType.id = 1;

			question.solution = quesLI.find(".solution").val();

			var optionsList = quesLI.find(".options-list");
			question.options = new Array();
			for (var j = 0; j < optionsList.children().length; j++) {
				var optLi = optionsList.children().eq(j);
				var opt = {};
				opt.opt = optLi.find(".option-content").val();
				opt.formatType = {};
				opt.formatType.id = 1;
				if (type == "SingleSelect" && quesLI.find("input:radio[id=" + j + "_" + questionId + "]").is(":checked")) {
					opt.answer = true;
				}
				if (type == "MultiSelect" && quesLI.find("input:checkbox[id=" + j + "_" + questionId + "]").is(":checked")) {
					opt.answer = true;
				}
				question.options.push(opt);
			}
			questions.push(question);
		}
		alert(JSON.stringify(questions));
		TestMgtService.addTestQuestions(createdTestId, questions, addTestQuestions_Result);

	}

	function addTestQuestions_Result(data) {
		alert("Added Questions");
	}



	return {
		getTestCategories: getTestCategories,
		getTestCategories_Result_Creation: getTestCategories_Result_Creation,
		addTest: addTest,
		addTest_Result: addTest_Result,
	};

})();